<template>
  <div class="collection">
    <el-tabs type="border-card" @tab-click="tabClick" v-model="activeName1">
      <template v-for="item in tableHeader">
        <el-tab-pane
          :name="item.position"
          :label="item.name + '-' + item.position"
          class="collection-item"
        >
          <template v-if="activeName1 == item.position">
            <div class="collection-item1">
              <el-tabs
                type="border-card"
                v-model="activeName[item.position]"
                class="collection-item1-1"
              >
                <el-tab-pane label="用电信息" name="first">
                  <ElectricityInfo
                    v-if="activeName[item.position] == 'first'"
                    :ruleForm="ruleForm"
                    :position="item.position + ''"
                    @calculateFormulas="calculateFormula"
                  ></ElectricityInfo>
                </el-tab-pane>
                <el-tab-pane label="抄见电量" name="second">
                  <ReadingPower
                    :position="item.position + ''"
                    v-if="activeName[item.position] == 'second'"
                  ></ReadingPower>
                </el-tab-pane>
                <el-tab-pane label="当前电价" name="third">
                  <CurrentEle
                    :position="item.position + ''"
                    v-if="activeName[item.position] == 'third'"
                  ></CurrentEle>
                </el-tab-pane>
                <el-tab-pane label="核算方案" name="fourth">
                  <NucleicProtocol
                    :position="item.position + ''"
                    v-if="activeName[item.position] == 'fourth'"
                  ></NucleicProtocol>
                </el-tab-pane>
                <el-tab-pane label="核算结果" name="five">
                  <NucleicResult
                    :position="item.position + ''"
                    v-if="activeName[item.position] == 'five'"
                  ></NucleicResult>
                </el-tab-pane>
                <el-tab-pane label="用户信息" name="six">
                  <UserInfo
                    v-if="activeName[item.position] == 'six'"
                  ></UserInfo>
                </el-tab-pane>
                <el-tab-pane label="收费" name="seven">
                  <Charge
                    :position="item.position + ''"
                    v-if="activeName[item.position] == 'seven'"
                  ></Charge>
                </el-tab-pane>
              </el-tabs>
              <div class="collection-item1-2">
                核算员：<el-input v-model="input" placeholder="核算员" />
                核算日期：<el-date-picker
                  v-model="value1"
                  type="date"
                  placeholder=""
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                />
              </div>
            </div>
            <div class="collection-item2">
              <div class="collection-item2-2 collection-w">
                <ul>
                  <li v-for="item in accountingList">
                    {{ item.newFormula ? item.newFormula : item.formula }}
                  </li>
                </ul>
              </div>
              <div class="collection-item2-1">
                <el-button @click="accountingData">核算</el-button>
              </div>
            </div>
          </template>
        </el-tab-pane>
      </template>
    </el-tabs>
  </div>
</template>
<script setup>
import { ref, onMounted, reactive, watch } from "vue";
import { EnergyData } from "@/utils/MeterReadingAndVerification.js";
import { lineLossData } from "@/gm/meterLabel.js";
import ElectricityInfo from "../../user/electricityInfo.vue";
import ReadingPower from "../../user/readingPower.vue";
import CurrentEle from "../../user/currentEle.vue";
import NucleicProtocol from "../../user/nucleicProtocol.vue";
import NucleicResult from "../../user/nucleicResult.vue";
import UserInfo from "../../user/userInfo.vue";
import Charge from "../../user/charge.vue";
import { useAppStore } from "@/stores";
import { storeToRefs } from "pinia";
const useApp = useAppStore();
let {
  monthMeterReading,
  currentEleType,
  lossParameters,
  currentAccountingData,
  receivedData,
  calculationData,
} = storeToRefs(useApp);

const tabPosition = ref("left");
const title = ref("用户");
const props = defineProps({
  currentData: Object,
});
const tableHeader = ref([]);
// console.log(lineLossData);
const tableData = lineLossData;
const activeName = ref([]);
const activeName1 = ref();
const input = ref("");
const value1 = ref();
const accountingList = ref([]);
const flag = ref(false);
const ruleForm = reactive({
  eleType: "",
  transformer: "非标",
  kva: "30kVA",
  voltageLevel: "小与1kV",
  powerFactor: "0.8",
  accountingPlan: "",
});

onMounted(() => {
  //数据监听
  watch(
    currentEleType.value,
    (newValue, oldValue) => {
      if (
        newValue[activeName1.value] &&
        newValue[activeName1.value] != undefined
      ) {
        flag.value = false;
        ruleForm.eleType = newValue[activeName1.value].name;
      }
    },
    { immediate: true },
    { deep: true }
  );
  watch(
    lossParameters.value,
    (newValue, oldValue) => {
      if (
        newValue[activeName1.value] &&
        newValue[activeName1.value] != undefined
      ) {
        flag.value = false;
        ruleForm.kva = newValue[activeName1.value].capacity + "kVA";
      }
    },
    { immediate: true },
    { deep: true }
  );
  watch(
    ruleForm,
    (newValue, oldValue) => {
      // console.log(newValue, flag.value);
      if (activeName1.value != undefined && activeName1.value && !flag.value)
        receivedData.value[activeName1.value] = JSON.parse(
          JSON.stringify(newValue)
        ); //核收用户数据
    },
    { immediate: true },
    { deep: true }
  );
  watch(
    activeName1,
    (newValue, oldValue) => {
      flag.value = true;
      if (receivedData.value[newValue]) {
        let newRuleForm = JSON.parse(
          JSON.stringify(receivedData.value[newValue])
        );
        ruleForm.eleType = newRuleForm.eleType;
        ruleForm.transformer = newRuleForm.transformer;
        ruleForm.kva = newRuleForm.kva;
        ruleForm.voltageLevel = newRuleForm.voltageLevel;
        ruleForm.powerFactor = newRuleForm.powerFactor;
        ruleForm.accountingPlan = newRuleForm.accountingPlan;
        accountingList.value = currentAccountingData.value[newValue];
      } else {
        ruleForm.eleType = "";
        ruleForm.transformer = "非标";
        ruleForm.kva = "30kVA";
        ruleForm.voltageLevel = "小与1kV";
        ruleForm.powerFactor = "0.8";
        ruleForm.accountingPlan = "";
        accountingList.value = [];
      }
    },
    { immediate: true },
    { deep: true }
  );
  tableHeader.value = props.currentData.children.filter(
    (item) => item.type != 2 && item.type != 6 && item.type != 3
  );
  if (props.currentData.type === 8) {
    activeName1.value = props.currentData.position;
    tableHeader.value = [props.currentData];
    activeName.value[activeName1.value] = "first";
  } else {
    if (tableHeader.value[0]) {
      activeName1.value = tableHeader.value[0].position;
      activeName.value[activeName1.value] = "first";
    }
  }
});

//核算方案
const accountingData = () => {
  if (ruleForm.eleType && ruleForm.accountingPlan) {
    let currentDataTemp = currentAccountingData.value[activeName1.value];
    let monthMeterTemp = monthMeterReading.value[activeName1.value];
    let currentEleTypeTemp = currentEleType.value[activeName1.value];
    let lossParametersTemp = lossParameters.value[activeName1.value];
    accountingList.value = currentAccountingData.value[activeName1.value]; //赋值
    let formulaArr = [];
    const propArr = [];
    const propValArr = [];
    currentDataTemp.forEach((item1) => {
      let newTempProp = item1.formula;
      // let formula = item1.formula;
      if (item1.formula) formulaArr.push(item1.formula);
      const classStr = []; //类参数
      //本月上月电能量 start
      if (monthMeterReading.value) {
        if (monthMeterTemp != undefined) {
          monthMeterTemp.forEach((item, index) => {
            let tempProp = item.label;
            if (!item.parm2) {
              let charToReplace1 = "当前";
              let replacementChar1 = "本月";
              tempProp = tempProp.replace(
                new RegExp(charToReplace1, "g"),
                replacementChar1
              );
            }
            let charToReplace = "电能";
            let replacementChar = "";
            tempProp = tempProp.replace(
              new RegExp(charToReplace, "g"),
              replacementChar
            );
            if (newTempProp) {
              let tempStr = newTempProp.replace(
                new RegExp(tempProp, "g"),
                item["value" + activeName1.value]
              );
              if (newTempProp != tempStr && newTempProp) {
                propArr.push(item.prop);
                propValArr.push(item["value" + activeName1.value]);
              }
            }
          });
        }
      }
      //用电类型匹配
      if (currentEleType.value) {
        let tempStr1 = "尖电价";
        let tempStr2 = "峰电价";
        let tempStr3 = "平电价";
        let tempStr4 = "谷电价";
        let tempStr5 = "代收基金";
        let tempStr6 = "容量点价";
        let tempStr7 = "需量电价";
        let tempPrice = currentEleTypeTemp.price;
        if (newTempProp) {
          let tempStr = newTempProp.replace(
            new RegExp(tempStr1, "g"),
            tempPrice.jian
          );
          if (newTempProp != tempStr && newTempProp) {
            propArr.push("jdj");
            propValArr.push(tempPrice.jian);
          }
          let tempStr01 = newTempProp.replace(
            new RegExp(tempStr2, "g"),
            tempPrice.feng
          );
          if (newTempProp != tempStr01 && newTempProp) {
            propArr.push("fdj");
            propValArr.push(tempPrice.feng);
          }
          let tempStr02 = newTempProp.replace(
            new RegExp(tempStr3, "g"),
            tempPrice.ping
          );
          if (newTempProp != tempStr02 && newTempProp) {
            propArr.push("pdj");
            propValArr.push(tempPrice.ping);
          }
          let tempStr03 = newTempProp.replace(
            new RegExp(tempStr4, "g"),
            tempPrice.gu
          );
          if (newTempProp != tempStr03 && newTempProp) {
            propArr.push("gdj");
            propValArr.push(tempPrice.gu);
          }
          let tempStr04 = newTempProp.replace(
            new RegExp(tempStr5, "g"),
            tempPrice.collectionFund
          );
          if (newTempProp != tempStr04 && newTempProp) {
            propArr.push("dsjj");
            propValArr.push(tempPrice.collectionFund);
          }
          let tempStr05 = newTempProp.replace(
            new RegExp(tempStr6, "g"),
            tempPrice.capacity
          );
          if (newTempProp != tempStr05 && newTempProp) {
            propArr.push("rldj");
            propValArr.push(tempPrice.capacity);
          }
          let tempStr06 = newTempProp.replace(
            new RegExp(tempStr7, "g"),
            tempPrice.demand
          );
          if (newTempProp != tempStr06 && newTempProp) {
            propArr.push("xldj");
            propValArr.push(tempPrice.demand);
          }
        }
      }
      //核算结果 铁损率对比
      if (lossParameters.value) {
        let tempStr1 = "有功铁损率";
        let tempStr2 = "无功铁损率";
        let tempStr3 = "每小时有功铁损";
        let tempStr4 = "每小时无功铁损";
        let tempPrice = lossParametersTemp;
        if (newTempProp && tempPrice) {
          let tempStr = newTempProp.replace(
            new RegExp(tempStr1, "g"),
            tempPrice.activeCopperLossRate
          );
          if (newTempProp != tempStr && newTempProp) {
            propArr.push("ygtsl");
            propValArr.push(tempPrice.activeCopperLossRate);
          }
          let tempStr01 = newTempProp.replace(
            new RegExp(tempStr2, "g"),
            tempPrice.reactiveCopperLossRate
          );
          if (newTempProp != tempStr01 && newTempProp) {
            propArr.push("wgtsl");
            propValArr.push(tempPrice.reactiveCopperLossRate);
          }
          let tempStr02 = newTempProp.replace(
            new RegExp(tempStr3, "g"),
            tempPrice.activeIronLossHour
          );
          if (newTempProp != tempStr02 && newTempProp) {
            propArr.push("mxsygts");
            propValArr.push(tempPrice.activeIronLossHour);
          }
          let tempStr03 = newTempProp.replace(
            new RegExp(tempStr4, "g"),
            tempPrice.reactiveIronLossHour
          );
          if (newTempProp != tempStr03 && newTempProp) {
            propArr.push("mxswgts");
            propValArr.push(tempPrice.reactiveIronLossHour);
          }
        }
      }
      //力调系数
      //电压变化、电流变化
      if (newTempProp) {
        let tableHeaderTemp = tableHeader.value.filter(
          (item) => item.position === activeName1.value
        );
        if (tableHeaderTemp[0]) {
          // let tempStr = newTempProp.replace(
          //   new RegExp("电压变化", "g"),
          //   "1/1"
          // );
          // if (tempStr != newTempProp && newTempProp) {
          propArr.push("dybh");
          propValArr.push(tableHeaderTemp[0].ptRatio);
          // }
          // let tempStr1 = newTempProp.replace(
          //   new RegExp("电流变化", "g"),
          //   "50/5"
          // );
          // if (tempStr1 != newTempProp && newTempProp) {
          propArr.push("dlbh");
          propValArr.push(tableHeaderTemp[0].ctRatio);
          console.log(propArr);
          console.log(propValArr);
          // }
        }
      }
    });
    if (formulaArr.length > 0 && propArr.length > 0) {
      // console.log("核算列表", formulaArr, propArr, propValArr);
      getDataIndex(propArr, propValArr, formulaArr);
    }
  } else {
    ElMessage({
      message: "请选择用电类型、核算方案",
      type: "warning",
    });
  }
};
const getDataIndex = (propArr, propValArr, newTempProp) => {
  const classParm = [
    "syfxygfl1",
    "syfxygfl2",
    "syfxygfl3",
    "syfxygfl4",
    "syfxygz",
    "sywgz",
    "syzxygfl1",
    "syzxygfl2",
    "syzxygfl3",
    "syzxygfl4",
    "syzxygz",
    "dsjj",
    "ltxs",
    "byqrl",
    "rldj",
    "jdj",
    "fdj",
    "pdj",
    "wgtsl",
    "ygtsl",
    "byfxygfl1",
    "byfxygfl2",
    "byfxygfl3",
    "byfxygfl4",
    "byfxygz",
    "bywgz",
    "byzxygfl1",
    "byzxygfl2",
    "byzxygfl3",
    "byzxygfl4",
    "byzxygz",
    "mxswgts",
    "mxsygts",
    "dybh",
    "dlbh",
    "gdj",
    "xldj",
  ];
  let newArr = [];
  for (let i = 0; i < propArr.length; i++) {
    let index = classParm.findIndex((item) => item === propArr[i]);
    newArr[index] = propValArr[i];
  }
  newArr[37] = newTempProp;

  let energyData = new EnergyData(
    newArr[0],
    newArr[1],
    newArr[2],
    newArr[3],
    newArr[4],
    newArr[5],
    newArr[6],
    newArr[7],
    newArr[8],
    newArr[9],
    newArr[10],
    newArr[11],
    newArr[12],
    newArr[13],
    newArr[14],
    newArr[15],
    newArr[16],
    newArr[17],
    newArr[18],
    newArr[19],
    newArr[20],
    newArr[21],
    newArr[22],
    newArr[23],
    newArr[24],
    newArr[25],
    newArr[26],
    newArr[27],
    newArr[28],
    newArr[29],
    newArr[30],
    newArr[31],
    newArr[32],
    newArr[33],
    newArr[34],
    newArr[35],
    newArr[36],
    newArr[37]
  );
  energyData.calculate();
  //计算之后赋值
  result(energyData.mathStr, energyData.resStr);
  //核算结果界面 计算 参数：1计算公式2结果
  accountingParameters(newTempProp, energyData.resStr);
};
//计算之后赋值
const result = (mathStr, resStr) => {
  accountingList.value.forEach((item, index) => {
    if (item.formula) {
      item.newFormula =
        item.formula + "=" + mathStr[index] + "=" + resStr[index];
    }
  });
};
//核算参数
const accountingParameters = (data, result) => {
  let obj = {};
  data.forEach((item, index) => {
    let params = item.split("=");
    switch (params[0]) {
      case "有功铁损":
        obj.activeIRonLoss = result[index];
        break;
      case "无功铜损":
        obj.reactiveCopperLoss = result[index];
        break;
      case "无功铁损":
        obj.reactiveIRonLoss = result[index];
        break;
      case "实际力率":
        obj.actualRate = result[index];
        break;
      case "力调系数":
        obj.ltxs = result[index];
        break;
      case "有功总":
        obj.ygz = result[index];
        break;
      case "尖时段":
        obj.jsd = result[index];
        break;
      case "峰时段":
        obj.fsd = result[index];
        break;
      case "平时段":
        obj.psd = result[index];
        break;
      case "谷时段":
        obj.gsd = result[index];
        break;
      case "无功总":
        obj.wgz = result[index];
        break;
      case "尖时段电费":
        obj.jsddf = result[index];
        break;
      case "峰时段电费":
        obj.fsddf = result[index];
        break;
      case "平时段电费":
        obj.psddf = result[index];
        break;
      case "谷时段电费":
        obj.gsddf = result[index];
        break;
      case "总电费":
        obj.zdf = result[index];
        break;
      default:
        break;
    }
  });
  if (!isEmpty(obj)) {
    calculationData.value[activeName1.value] = obj;
  }
};
const isEmpty = (obj) => {
  return Object.keys(obj).length === 0;
};
//核算
const calculateFormula = (parm) => {
  flag.value = false;
  if (parm) ruleForm.accountingPlan = parm;
};
const tabClick = (val) => {
  let num = val.props.name;
  //tab 初始赋值
  if (activeName.value[num] === undefined) {
    activeName.value[num] = "first";
    flag.value = true;
  }
};
</script>

<style lang="scss" scoped>
.collection-item {
  display: flex;
  .collection-item1 {
    flex: 1;
    // .collection-item1-1 {
    //   height: 400px;
    // }
    .collection-item1-2 {
      display: flex;
      justify-content: end;
      margin-top: 10px;
      align-items: center;
      .el-input {
        width: 200px;
      }
    }
  }
  .collection-item2 {
    width: 300px;
    margin-left: 10px;
    .collection-item2-1 {
      margin-top: 10px;
      text-align: right;
      .el-button {
        width: 100px;
      }
    }
  }
  .collection-item2-2 {
    border: 1px solid #dcdfe6;
    overflow: scroll;
  }
  :deep(.el-textarea__inner) {
    //el_input中的隐藏属性
    resize: none; //禁止拉伸
    height: 300px;
  }
}
</style>
